package com.gobang.websocket.handler;

import com.fasterxml.jackson.databind.JsonNode;
import com.gobang.common.constant.BusinessErrorCode;
import com.gobang.common.exception.BusinessException;
import com.gobang.websocket.service.WebSocketPushService;
import com.gobang.websocket.session.WebSocketSessionManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

/**
 * 心跳消息处理器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class HeartbeatMessageHandler {

    private final WebSocketSessionManager webSocketSessionManager;
    private final WebSocketPushService webSocketPushService;

    /**
     * 处理心跳消息（type = ping）
     */
    public void handle(WebSocketSession session, JsonNode data) {
        if (session == null) {
            throw new BusinessException(BusinessErrorCode.WEBSOCKET_SESSION_NOT_FOUND, "会话不存在");
        }

        Long userId = extractUserId(session);
        String sessionId = session.getId();

        if (userId == null) {
            throw new BusinessException(BusinessErrorCode.WEBSOCKET_SESSION_NOT_FOUND, "会话未绑定用户");
        }

        // 更新心跳时间与在线状态
        webSocketSessionManager.updateHeartbeat(userId, sessionId);

        // 发送 heartbeat 响应
        webSocketPushService.sendHeartbeat(session);
    }

    private Long extractUserId(WebSocketSession session) {
        Object attr = session.getAttributes().get("userId");
        if (attr instanceof Long l) {
            return l;
        }
        if (attr instanceof Integer i) {
            return i.longValue();
        }
        if (attr != null) {
            try {
                return Long.valueOf(attr.toString());
            } catch (NumberFormatException e) {
                log.warn("无法从 WebSocketSession 属性解析 userId: {}", attr);
            }
        }
        return null;
    }
}
